home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / ViePratique / ArchiFacile / ArchiFacileSetup.exe / {app} / nw.pak / Unnamed File 001030.unknown < prev    next >
Text File  |  2014-10-14  |  62KB  |  483 lines

  1. WebInspector.AuditsPanel=function()
  2. {WebInspector.PanelWithSidebarTree.call(this,"audits");this.registerRequiredCSS("panelEnablerView.css");this.registerRequiredCSS("auditsPanel.css");this.auditsTreeElement=new WebInspector.SidebarSectionTreeElement("",{},true);this.sidebarTree.appendChild(this.auditsTreeElement);this.auditsTreeElement.listItemElement.classList.add("hidden");this.auditsItemTreeElement=new WebInspector.AuditsSidebarTreeElement(this);this.auditsTreeElement.appendChild(this.auditsItemTreeElement);this.auditResultsTreeElement=new WebInspector.SidebarSectionTreeElement(WebInspector.UIString("RESULTS"),{},true);this.sidebarTree.appendChild(this.auditResultsTreeElement);this.auditResultsTreeElement.expand();this._constructCategories();this._auditController=new WebInspector.AuditController(this);this._launcherView=new WebInspector.AuditLauncherView(this._auditController);for(var id in this.categoriesById)
  3. this._launcherView.addCategory(this.categoriesById[id]);}
  4. WebInspector.AuditsPanel.prototype={canSearch:function()
  5. {return false;},get categoriesById()
  6. {return this._auditCategoriesById;},addCategory:function(category)
  7. {this.categoriesById[category.id]=category;this._launcherView.addCategory(category);},getCategory:function(id)
  8. {return this.categoriesById[id];},_constructCategories:function()
  9. {this._auditCategoriesById={};for(var categoryCtorID in WebInspector.AuditCategories){var auditCategory=new WebInspector.AuditCategories[categoryCtorID]();auditCategory._id=categoryCtorID;this.categoriesById[categoryCtorID]=auditCategory;}},auditFinishedCallback:function(mainResourceURL,results)
  10. {var children=this.auditResultsTreeElement.children;var ordinal=1;for(var i=0;i<children.length;++i){if(children[i].mainResourceURL===mainResourceURL)
  11. ordinal++;}
  12. var resultTreeElement=new WebInspector.AuditResultSidebarTreeElement(this,results,mainResourceURL,ordinal);this.auditResultsTreeElement.appendChild(resultTreeElement);resultTreeElement.revealAndSelect();},showResults:function(categoryResults)
  13. {if(!categoryResults._resultView)
  14. categoryResults._resultView=new WebInspector.AuditResultView(categoryResults);this.visibleView=categoryResults._resultView;},showLauncherView:function()
  15. {this.visibleView=this._launcherView;},get visibleView()
  16. {return this._visibleView;},set visibleView(x)
  17. {if(this._visibleView===x)
  18. return;if(this._visibleView)
  19. this._visibleView.detach();this._visibleView=x;if(x)
  20. x.show(this.mainElement());},wasShown:function()
  21. {WebInspector.Panel.prototype.wasShown.call(this);if(!this._visibleView)
  22. this.auditsItemTreeElement.select();},clearResults:function()
  23. {this.auditsItemTreeElement.revealAndSelect();this.auditResultsTreeElement.removeChildren();},__proto__:WebInspector.PanelWithSidebarTree.prototype}
  24. WebInspector.AuditCategoryImpl=function(displayName)
  25. {this._displayName=displayName;this._rules=[];}
  26. WebInspector.AuditCategoryImpl.prototype={get id()
  27. {return this._id;},get displayName()
  28. {return this._displayName;},addRule:function(rule,severity)
  29. {rule.severity=severity;this._rules.push(rule);},run:function(requests,ruleResultCallback,categoryDoneCallback,progress)
  30. {this._ensureInitialized();var remainingRulesCount=this._rules.length;progress.setTotalWork(remainingRulesCount);function callbackWrapper(result)
  31. {ruleResultCallback(result);progress.worked();if(!--remainingRulesCount)
  32. categoryDoneCallback();}
  33. for(var i=0;i<this._rules.length;++i)
  34. this._rules[i].run(requests,callbackWrapper,progress);},_ensureInitialized:function()
  35. {if(!this._initialized){if("initialize"in this)
  36. this.initialize();this._initialized=true;}}}
  37. WebInspector.AuditRule=function(id,displayName)
  38. {this._id=id;this._displayName=displayName;}
  39. WebInspector.AuditRule.Severity={Info:"info",Warning:"warning",Severe:"severe"}
  40. WebInspector.AuditRule.SeverityOrder={"info":3,"warning":2,"severe":1}
  41. WebInspector.AuditRule.prototype={get id()
  42. {return this._id;},get displayName()
  43. {return this._displayName;},set severity(severity)
  44. {this._severity=severity;},run:function(requests,callback,progress)
  45. {if(progress.isCanceled())
  46. return;var result=new WebInspector.AuditRuleResult(this.displayName);result.severity=this._severity;this.doRun(requests,result,callback,progress);},doRun:function(requests,result,callback,progress)
  47. {throw new Error("doRun() not implemented");}}
  48. WebInspector.AuditCategoryResult=function(category)
  49. {this.title=category.displayName;this.ruleResults=[];}
  50. WebInspector.AuditCategoryResult.prototype={addRuleResult:function(ruleResult)
  51. {this.ruleResults.push(ruleResult);}}
  52. WebInspector.AuditRuleResult=function(value,expanded,className)
  53. {this.value=value;this.className=className;this.expanded=expanded;this.violationCount=0;this._formatters={r:WebInspector.AuditRuleResult.linkifyDisplayName};var standardFormatters=Object.keys(String.standardFormatters);for(var i=0;i<standardFormatters.length;++i)
  54. this._formatters[standardFormatters[i]]=String.standardFormatters[standardFormatters[i]];}
  55. WebInspector.AuditRuleResult.linkifyDisplayName=function(url)
  56. {return WebInspector.linkifyURLAsNode(url,WebInspector.displayNameForURL(url));}
  57. WebInspector.AuditRuleResult.resourceDomain=function(domain)
  58. {return domain||WebInspector.UIString("[empty domain]");}
  59. WebInspector.AuditRuleResult.prototype={addChild:function(value,expanded,className)
  60. {if(!this.children)
  61. this.children=[];var entry=new WebInspector.AuditRuleResult(value,expanded,className);this.children.push(entry);return entry;},addURL:function(url)
  62. {this.addChild(WebInspector.AuditRuleResult.linkifyDisplayName(url));},addURLs:function(urls)
  63. {for(var i=0;i<urls.length;++i)
  64. this.addURL(urls[i]);},addSnippet:function(snippet)
  65. {this.addChild(snippet,false,"source-code");},addFormatted:function(format,vararg)
  66. {var substitutions=Array.prototype.slice.call(arguments,1);var fragment=document.createDocumentFragment();function append(a,b)
  67. {if(!(b instanceof Node))
  68. b=document.createTextNode(b);a.appendChild(b);return a;}
  69. var formattedResult=String.format(format,substitutions,this._formatters,fragment,append).formattedResult;if(formattedResult instanceof Node)
  70. formattedResult.normalize();return this.addChild(formattedResult);}}
  71. WebInspector.AuditsSidebarTreeElement=function(panel)
  72. {this._panel=panel;this.small=false;WebInspector.SidebarTreeElement.call(this,"audits-sidebar-tree-item",WebInspector.UIString("Audits"),"",null,false);}
  73. WebInspector.AuditsSidebarTreeElement.prototype={onattach:function()
  74. {WebInspector.SidebarTreeElement.prototype.onattach.call(this);},onselect:function()
  75. {this._panel.showLauncherView();},get selectable()
  76. {return true;},refresh:function()
  77. {this.refreshTitles();},__proto__:WebInspector.SidebarTreeElement.prototype}
  78. WebInspector.AuditResultSidebarTreeElement=function(panel,results,mainResourceURL,ordinal)
  79. {this._panel=panel;this.results=results;this.mainResourceURL=mainResourceURL;WebInspector.SidebarTreeElement.call(this,"audit-result-sidebar-tree-item",String.sprintf("%s (%d)",mainResourceURL,ordinal),"",{},false);}
  80. WebInspector.AuditResultSidebarTreeElement.prototype={onselect:function()
  81. {this._panel.showResults(this.results);},get selectable()
  82. {return true;},__proto__:WebInspector.SidebarTreeElement.prototype}
  83. WebInspector.AuditRules={};WebInspector.AuditCategories={};WebInspector.AuditCategory=function()
  84. {}
  85. WebInspector.AuditCategory.prototype={get id()
  86. {},get displayName()
  87. {},run:function(requests,ruleResultCallback,categoryDoneCallback,progress)
  88. {}};WebInspector.AuditCategories.PagePerformance=function(){WebInspector.AuditCategoryImpl.call(this,WebInspector.AuditCategories.PagePerformance.AuditCategoryName);}
  89. WebInspector.AuditCategories.PagePerformance.AuditCategoryName=WebInspector.UIString("Web Page Performance");WebInspector.AuditCategories.PagePerformance.prototype={initialize:function()
  90. {this.addRule(new WebInspector.AuditRules.UnusedCssRule(),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditRules.CssInHeadRule(),WebInspector.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.StylesScriptsOrderRule(),WebInspector.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.VendorPrefixedCSSProperties(),WebInspector.AuditRule.Severity.Warning);},__proto__:WebInspector.AuditCategoryImpl.prototype}
  91. WebInspector.AuditCategories.NetworkUtilization=function(){WebInspector.AuditCategoryImpl.call(this,WebInspector.AuditCategories.NetworkUtilization.AuditCategoryName);}
  92. WebInspector.AuditCategories.NetworkUtilization.AuditCategoryName=WebInspector.UIString("Network Utilization");WebInspector.AuditCategories.NetworkUtilization.prototype={initialize:function()
  93. {this.addRule(new WebInspector.AuditRules.GzipRule(),WebInspector.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.ImageDimensionsRule(),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditRules.CookieSizeRule(400),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditRules.StaticCookielessRule(5),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditRules.CombineJsResourcesRule(2),WebInspector.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.CombineCssResourcesRule(2),WebInspector.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.MinimizeDnsLookupsRule(4),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditRules.ParallelizeDownloadRule(4,10,0.5),WebInspector.AuditRule.Severity.Warning);this.addRule(new WebInspector.AuditRules.BrowserCacheControlRule(),WebInspector.AuditRule.Severity.Severe);this.addRule(new WebInspector.AuditRules.ProxyCacheControlRule(),WebInspector.AuditRule.Severity.Warning);},__proto__:WebInspector.AuditCategoryImpl.prototype};WebInspector.AuditController=function(auditsPanel)
  94. {this._auditsPanel=auditsPanel;WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.Load,this._didMainResourceLoad,this);}
  95. WebInspector.AuditController.prototype={_executeAudit:function(categories,resultCallback)
  96. {this._progress.setTitle(WebInspector.UIString("Running audit"));function ruleResultReadyCallback(categoryResult,ruleResult)
  97. {if(ruleResult&&ruleResult.children)
  98. categoryResult.addRuleResult(ruleResult);if(this._progress.isCanceled())
  99. this._progress.done();}
  100. var results=[];var mainResourceURL=WebInspector.resourceTreeModel.inspectedPageURL();var categoriesDone=0;function categoryDoneCallback()
  101. {if(++categoriesDone!==categories.length)
  102. return;this._progress.done();resultCallback(mainResourceURL,results)}
  103. var requests=WebInspector.networkLog.requests.slice();var compositeProgress=new WebInspector.CompositeProgress(this._progress);var subprogresses=[];for(var i=0;i<categories.length;++i)
  104. subprogresses.push(compositeProgress.createSubProgress());for(var i=0;i<categories.length;++i){var category=categories[i];var result=new WebInspector.AuditCategoryResult(category);results.push(result);category.run(requests,ruleResultReadyCallback.bind(this,result),categoryDoneCallback.bind(this),subprogresses[i]);}},_auditFinishedCallback:function(launcherCallback,mainResourceURL,results)
  105. {this._auditsPanel.auditFinishedCallback(mainResourceURL,results);if(!this._progress.isCanceled())
  106. launcherCallback();},initiateAudit:function(categoryIds,progress,runImmediately,startedCallback,finishedCallback)
  107. {if(!categoryIds||!categoryIds.length)
  108. return;this._progress=progress;var categories=[];for(var i=0;i<categoryIds.length;++i)
  109. categories.push(this._auditsPanel.categoriesById[categoryIds[i]]);function startAuditWhenResourcesReady()
  110. {startedCallback();this._executeAudit(categories,this._auditFinishedCallback.bind(this,finishedCallback));}
  111. if(runImmediately)
  112. startAuditWhenResourcesReady.call(this);else
  113. this._reloadResources(startAuditWhenResourcesReady.bind(this));WebInspector.userMetrics.AuditsStarted.record();},_reloadResources:function(callback)
  114. {this._pageReloadCallback=callback;WebInspector.resourceTreeModel.reloadPage();},_didMainResourceLoad:function()
  115. {if(this._pageReloadCallback){var callback=this._pageReloadCallback;delete this._pageReloadCallback;callback();}},clearResults:function()
  116. {this._auditsPanel.clearResults();}};WebInspector.AuditFormatters=function()
  117. {}
  118. WebInspector.AuditFormatters.Registry={text:function(text)
  119. {return document.createTextNode(text);},snippet:function(snippetText)
  120. {var div=document.createElement("div");div.textContent=snippetText;div.className="source-code";return div;},concat:function()
  121. {var parent=document.createElement("span");for(var arg=0;arg<arguments.length;++arg)
  122. parent.appendChild(WebInspector.auditFormatters.apply(arguments[arg]));return parent;},url:function(url,displayText,allowExternalNavigation)
  123. {var a=document.createElement("a");a.href=sanitizeHref(url);a.title=url;a.textContent=displayText||url;if(allowExternalNavigation)
  124. a.target="_blank";return a;},resourceLink:function(url,line)
  125. {return WebInspector.linkifyResourceAsNode(url,line,"console-message-url webkit-html-resource-link");}};WebInspector.AuditFormatters.prototype={apply:function(value)
  126. {var formatter;var type=typeof value;var args;switch(type){case"string":case"boolean":case"number":formatter=WebInspector.AuditFormatters.Registry.text;args=[value.toString()];break;case"object":if(value instanceof Node)
  127. return value;if(value instanceof Array){formatter=WebInspector.AuditFormatters.Registry.concat;args=value;}else if(value.type&&value.arguments){formatter=WebInspector.AuditFormatters.Registry[value.type];args=value.arguments;}}
  128. if(!formatter)
  129. throw"Invalid value or formatter: "+type+JSON.stringify(value);return formatter.apply(null,args);},partiallyApply:function(formatters,thisArgument,value)
  130. {if(value instanceof Array)
  131. return value.map(this.partiallyApply.bind(this,formatters,thisArgument));if(typeof value==="object"&&typeof formatters[value.type]==="function"&&value.arguments)
  132. return formatters[value.type].apply(thisArgument,value.arguments);return value;}}
  133. WebInspector.auditFormatters=new WebInspector.AuditFormatters();;WebInspector.AuditLauncherView=function(auditController)
  134. {WebInspector.VBox.call(this);this.setMinimumSize(100,25);this._auditController=auditController;this._categoryIdPrefix="audit-category-item-";this._auditRunning=false;this.element.classList.add("audit-launcher-view");this.element.classList.add("panel-enabler-view");this._contentElement=document.createElement("div");this._contentElement.className="audit-launcher-view-content";this.element.appendChild(this._contentElement);this._boundCategoryClickListener=this._categoryClicked.bind(this);this._resetResourceCount();this._sortedCategories=[];this._headerElement=document.createElement("h1");this._headerElement.className="no-audits";this._headerElement.textContent=WebInspector.UIString("No audits to run");this._contentElement.appendChild(this._headerElement);WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestStarted,this._onRequestStarted,this);WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestFinished,this._onRequestFinished,this);var defaultSelectedAuditCategory={};defaultSelectedAuditCategory[WebInspector.AuditLauncherView.AllCategoriesKey]=true;this._selectedCategoriesSetting=WebInspector.settings.createSetting("selectedAuditCategories",defaultSelectedAuditCategory);}
  135. WebInspector.AuditLauncherView.AllCategoriesKey="__AllCategories";WebInspector.AuditLauncherView.prototype={_resetResourceCount:function()
  136. {this._loadedResources=0;this._totalResources=0;},_onRequestStarted:function(event)
  137. {var request=(event.data);if(request.type===WebInspector.resourceTypes.WebSocket)
  138. return;++this._totalResources;this._updateResourceProgress();},_onRequestFinished:function(event)
  139. {var request=(event.data);if(request.type===WebInspector.resourceTypes.WebSocket)
  140. return;++this._loadedResources;this._updateResourceProgress();},addCategory:function(category)
  141. {if(!this._sortedCategories.length)
  142. this._createLauncherUI();var selectedCategories=this._selectedCategoriesSetting.get();var categoryElement=this._createCategoryElement(category.displayName,category.id);category._checkboxElement=categoryElement.firstChild;if(this._selectAllCheckboxElement.checked||selectedCategories[category.displayName]){category._checkboxElement.checked=true;++this._currentCategoriesCount;}
  143. function compareCategories(a,b)
  144. {var aTitle=a.displayName||"";var bTitle=b.displayName||"";return aTitle.localeCompare(bTitle);}
  145. var insertBefore=insertionIndexForObjectInListSortedByFunction(category,this._sortedCategories,compareCategories);this._categoriesElement.insertBefore(categoryElement,this._categoriesElement.children[insertBefore]);this._sortedCategories.splice(insertBefore,0,category);this._selectedCategoriesUpdated();},_setAuditRunning:function(auditRunning)
  146. {if(this._auditRunning===auditRunning)
  147. return;this._auditRunning=auditRunning;this._updateButton();this._toggleUIComponents(this._auditRunning);if(this._auditRunning)
  148. this._startAudit();else
  149. this._stopAudit();},_startAudit:function()
  150. {var catIds=[];for(var category=0;category<this._sortedCategories.length;++category){if(this._sortedCategories[category]._checkboxElement.checked)
  151. catIds.push(this._sortedCategories[category].id);}
  152. this._resetResourceCount();this._progressIndicator=new WebInspector.ProgressIndicator();this._buttonContainerElement.appendChild(this._progressIndicator.element);this._displayResourceLoadingProgress=true;function onAuditStarted()
  153. {this._displayResourceLoadingProgress=false;}
  154. this._auditController.initiateAudit(catIds,this._progressIndicator,this._auditPresentStateElement.checked,onAuditStarted.bind(this),this._setAuditRunning.bind(this,false));},_stopAudit:function()
  155. {this._displayResourceLoadingProgress=false;this._progressIndicator.cancel();this._progressIndicator.done();delete this._progressIndicator;},_toggleUIComponents:function(disable)
  156. {this._selectAllCheckboxElement.disabled=disable;this._categoriesElement.disabled=disable;this._auditPresentStateElement.disabled=disable;this._auditReloadedStateElement.disabled=disable;},_launchButtonClicked:function(event)
  157. {this._setAuditRunning(!this._auditRunning);},_clearButtonClicked:function()
  158. {this._auditController.clearResults();},_selectAllClicked:function(checkCategories,userGesture)
  159. {var childNodes=this._categoriesElement.childNodes;for(var i=0,length=childNodes.length;i<length;++i)
  160. childNodes[i].firstChild.checked=checkCategories;this._currentCategoriesCount=checkCategories?this._sortedCategories.length:0;this._selectedCategoriesUpdated(userGesture);},_categoryClicked:function(event)
  161. {this._currentCategoriesCount+=event.target.checked?1:-1;this._selectAllCheckboxElement.checked=this._currentCategoriesCount===this._sortedCategories.length;this._selectedCategoriesUpdated(true);},_createCategoryElement:function(title,id)
  162. {var labelElement=document.createElement("label");labelElement.id=this._categoryIdPrefix+id;var element=document.createElement("input");element.type="checkbox";if(id!=="")
  163. element.addEventListener("click",this._boundCategoryClickListener,false);labelElement.appendChild(element);labelElement.appendChild(document.createTextNode(title));labelElement.__displayName=title;return labelElement;},_createLauncherUI:function()
  164. {this._headerElement=document.createElement("h1");this._headerElement.textContent=WebInspector.UIString("Select audits to run");for(var child=0;child<this._contentElement.children.length;++child)
  165. this._contentElement.removeChild(this._contentElement.children[child]);this._contentElement.appendChild(this._headerElement);function handleSelectAllClick(event)
  166. {this._selectAllClicked(event.target.checked,true);}
  167. var categoryElement=this._createCategoryElement(WebInspector.UIString("Select All"),"");categoryElement.id="audit-launcher-selectall";this._selectAllCheckboxElement=categoryElement.firstChild;this._selectAllCheckboxElement.checked=this._selectedCategoriesSetting.get()[WebInspector.AuditLauncherView.AllCategoriesKey];this._selectAllCheckboxElement.addEventListener("click",handleSelectAllClick.bind(this),false);this._contentElement.appendChild(categoryElement);this._categoriesElement=this._contentElement.createChild("fieldset","audit-categories-container");this._currentCategoriesCount=0;this._contentElement.createChild("div","flexible-space");this._buttonContainerElement=this._contentElement.createChild("div","button-container");var labelElement=this._buttonContainerElement.createChild("label");this._auditPresentStateElement=labelElement.createChild("input");this._auditPresentStateElement.name="audit-mode";this._auditPresentStateElement.type="radio";this._auditPresentStateElement.checked=true;this._auditPresentStateLabelElement=document.createTextNode(WebInspector.UIString("Audit Present State"));labelElement.appendChild(this._auditPresentStateLabelElement);labelElement=this._buttonContainerElement.createChild("label");this._auditReloadedStateElement=labelElement.createChild("input");this._auditReloadedStateElement.name="audit-mode";this._auditReloadedStateElement.type="radio";labelElement.appendChild(document.createTextNode("Reload Page and Audit on Load"));this._launchButton=this._buttonContainerElement.createChild("button");this._launchButton.textContent=WebInspector.UIString("Run");this._launchButton.addEventListener("click",this._launchButtonClicked.bind(this),false);this._clearButton=this._buttonContainerElement.createChild("button");this._clearButton.textContent=WebInspector.UIString("Clear");this._clearButton.addEventListener("click",this._clearButtonClicked.bind(this),false);this._selectAllClicked(this._selectAllCheckboxElement.checked);},_updateResourceProgress:function()
  168. {if(this._displayResourceLoadingProgress)
  169. this._progressIndicator.setTitle(WebInspector.UIString("Loading (%d of %d)",this._loadedResources,this._totalResources));},_selectedCategoriesUpdated:function(userGesture)
  170. {var selectedCategories=userGesture?{}:this._selectedCategoriesSetting.get();var childNodes=this._categoriesElement.childNodes;for(var i=0,length=childNodes.length;i<length;++i)
  171. selectedCategories[childNodes[i].__displayName]=childNodes[i].firstChild.checked;selectedCategories[WebInspector.AuditLauncherView.AllCategoriesKey]=this._selectAllCheckboxElement.checked;this._selectedCategoriesSetting.set(selectedCategories);this._updateButton();},_updateButton:function()
  172. {this._launchButton.textContent=this._auditRunning?WebInspector.UIString("Stop"):WebInspector.UIString("Run");this._launchButton.disabled=!this._currentCategoriesCount;},__proto__:WebInspector.VBox.prototype};WebInspector.AuditResultView=function(categoryResults)
  173. {WebInspector.SidebarPaneStack.call(this);this.setMinimumSize(100,25);this.element.classList.add("audit-result-view","fill");function categorySorter(a,b){return(a.title||"").localeCompare(b.title||"");}
  174. categoryResults.sort(categorySorter);for(var i=0;i<categoryResults.length;++i)
  175. this.addPane(new WebInspector.AuditCategoryResultPane(categoryResults[i]));}
  176. WebInspector.AuditResultView.prototype={__proto__:WebInspector.SidebarPaneStack.prototype}
  177. WebInspector.AuditCategoryResultPane=function(categoryResult)
  178. {WebInspector.SidebarPane.call(this,categoryResult.title);var treeOutlineElement=document.createElement("ol");this.bodyElement.classList.add("audit-result-tree");this.bodyElement.appendChild(treeOutlineElement);this._treeOutline=new TreeOutline(treeOutlineElement);this._treeOutline.expandTreeElementsWhenArrowing=true;function ruleSorter(a,b)
  179. {var result=WebInspector.AuditRule.SeverityOrder[a.severity||0]-WebInspector.AuditRule.SeverityOrder[b.severity||0];if(!result)
  180. result=(a.value||"").localeCompare(b.value||"");return result;}
  181. categoryResult.ruleResults.sort(ruleSorter);for(var i=0;i<categoryResult.ruleResults.length;++i){var ruleResult=categoryResult.ruleResults[i];var treeElement=this._appendResult(this._treeOutline,ruleResult,ruleResult.severity);treeElement.listItemElement.classList.add("audit-result");}
  182. this.expand();}
  183. WebInspector.AuditCategoryResultPane.prototype={_appendResult:function(parentTreeElement,result,severity)
  184. {var title="";if(typeof result.value==="string"){title=result.value;if(result.violationCount)
  185. title=String.sprintf("%s (%d)",title,result.violationCount);}
  186. var titleFragment=document.createDocumentFragment();if(severity){var severityElement=document.createElement("div");severityElement.className="severity-"+severity;titleFragment.appendChild(severityElement);}
  187. titleFragment.appendChild(document.createTextNode(title));var treeElement=new TreeElement(titleFragment,null,!!result.children);parentTreeElement.appendChild(treeElement);if(result.className)
  188. treeElement.listItemElement.classList.add(result.className);if(typeof result.value!=="string")
  189. treeElement.listItemElement.appendChild(WebInspector.auditFormatters.apply(result.value));if(result.children){for(var i=0;i<result.children.length;++i)
  190. this._appendResult(treeElement,result.children[i]);}
  191. if(result.expanded){treeElement.listItemElement.classList.remove("parent");treeElement.listItemElement.classList.add("parent-expanded");treeElement.expand();}
  192. return treeElement;},__proto__:WebInspector.SidebarPane.prototype};WebInspector.AuditRules.IPAddressRegexp=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;WebInspector.AuditRules.CacheableResponseCodes={200:true,203:true,206:true,300:true,301:true,410:true,304:true}
  193. WebInspector.AuditRules.getDomainToResourcesMap=function(requests,types,needFullResources)
  194. {var domainToResourcesMap={};for(var i=0,size=requests.length;i<size;++i){var request=requests[i];if(types&&types.indexOf(request.type)===-1)
  195. continue;var parsedURL=request.url.asParsedURL();if(!parsedURL)
  196. continue;var domain=parsedURL.host;var domainResources=domainToResourcesMap[domain];if(domainResources===undefined){domainResources=[];domainToResourcesMap[domain]=domainResources;}
  197. domainResources.push(needFullResources?request:request.url);}
  198. return domainToResourcesMap;}
  199. WebInspector.AuditRules.GzipRule=function()
  200. {WebInspector.AuditRule.call(this,"network-gzip",WebInspector.UIString("Enable gzip compression"));}
  201. WebInspector.AuditRules.GzipRule.prototype={doRun:function(requests,result,callback,progress)
  202. {var totalSavings=0;var compressedSize=0;var candidateSize=0;var summary=result.addChild("",true);for(var i=0,length=requests.length;i<length;++i){var request=requests[i];if(request.cached||request.statusCode===304)
  203. continue;if(this._shouldCompress(request)){var size=request.resourceSize;candidateSize+=size;if(this._isCompressed(request)){compressedSize+=size;continue;}
  204. var savings=2*size/3;totalSavings+=savings;summary.addFormatted("%r could save ~%s",request.url,Number.bytesToString(savings));result.violationCount++;}}
  205. if(!totalSavings){callback(null);return;}
  206. summary.value=WebInspector.UIString("Compressing the following resources with gzip could reduce their transfer size by about two thirds (~%s):",Number.bytesToString(totalSavings));callback(result);},_isCompressed:function(request)
  207. {var encodingHeader=request.responseHeaderValue("Content-Encoding");if(!encodingHeader)
  208. return false;return/\b(?:gzip|deflate)\b/.test(encodingHeader);},_shouldCompress:function(request)
  209. {return request.type.isTextType()&&request.parsedURL.host&&request.resourceSize!==undefined&&request.resourceSize>150;},__proto__:WebInspector.AuditRule.prototype}
  210. WebInspector.AuditRules.CombineExternalResourcesRule=function(id,name,type,resourceTypeName,allowedPerDomain)
  211. {WebInspector.AuditRule.call(this,id,name);this._type=type;this._resourceTypeName=resourceTypeName;this._allowedPerDomain=allowedPerDomain;}
  212. WebInspector.AuditRules.CombineExternalResourcesRule.prototype={doRun:function(requests,result,callback,progress)
  213. {var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(requests,[this._type],false);var penalizedResourceCount=0;var summary=result.addChild("",true);for(var domain in domainToResourcesMap){var domainResources=domainToResourcesMap[domain];var extraResourceCount=domainResources.length-this._allowedPerDomain;if(extraResourceCount<=0)
  214. continue;penalizedResourceCount+=extraResourceCount-1;summary.addChild(WebInspector.UIString("%d %s resources served from %s.",domainResources.length,this._resourceTypeName,WebInspector.AuditRuleResult.resourceDomain(domain)));result.violationCount+=domainResources.length;}
  215. if(!penalizedResourceCount){callback(null);return;}
  216. summary.value=WebInspector.UIString("There are multiple resources served from same domain. Consider combining them into as few files as possible.");callback(result);},__proto__:WebInspector.AuditRule.prototype}
  217. WebInspector.AuditRules.CombineJsResourcesRule=function(allowedPerDomain){WebInspector.AuditRules.CombineExternalResourcesRule.call(this,"page-externaljs",WebInspector.UIString("Combine external JavaScript"),WebInspector.resourceTypes.Script,"JavaScript",allowedPerDomain);}
  218. WebInspector.AuditRules.CombineJsResourcesRule.prototype={__proto__:WebInspector.AuditRules.CombineExternalResourcesRule.prototype}
  219. WebInspector.AuditRules.CombineCssResourcesRule=function(allowedPerDomain){WebInspector.AuditRules.CombineExternalResourcesRule.call(this,"page-externalcss",WebInspector.UIString("Combine external CSS"),WebInspector.resourceTypes.Stylesheet,"CSS",allowedPerDomain);}
  220. WebInspector.AuditRules.CombineCssResourcesRule.prototype={__proto__:WebInspector.AuditRules.CombineExternalResourcesRule.prototype}
  221. WebInspector.AuditRules.MinimizeDnsLookupsRule=function(hostCountThreshold){WebInspector.AuditRule.call(this,"network-minimizelookups",WebInspector.UIString("Minimize DNS lookups"));this._hostCountThreshold=hostCountThreshold;}
  222. WebInspector.AuditRules.MinimizeDnsLookupsRule.prototype={doRun:function(requests,result,callback,progress)
  223. {var summary=result.addChild("");var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(requests,null,false);for(var domain in domainToResourcesMap){if(domainToResourcesMap[domain].length>1)
  224. continue;var parsedURL=domain.asParsedURL();if(!parsedURL)
  225. continue;if(!parsedURL.host.search(WebInspector.AuditRules.IPAddressRegexp))
  226. continue;summary.addSnippet(domain);result.violationCount++;}
  227. if(!summary.children||summary.children.length<=this._hostCountThreshold){callback(null);return;}
  228. summary.value=WebInspector.UIString("The following domains only serve one resource each. If possible, avoid the extra DNS lookups by serving these resources from existing domains.");callback(result);},__proto__:WebInspector.AuditRule.prototype}
  229. WebInspector.AuditRules.ParallelizeDownloadRule=function(optimalHostnameCount,minRequestThreshold,minBalanceThreshold)
  230. {WebInspector.AuditRule.call(this,"network-parallelizehosts",WebInspector.UIString("Parallelize downloads across hostnames"));this._optimalHostnameCount=optimalHostnameCount;this._minRequestThreshold=minRequestThreshold;this._minBalanceThreshold=minBalanceThreshold;}
  231. WebInspector.AuditRules.ParallelizeDownloadRule.prototype={doRun:function(requests,result,callback,progress)
  232. {function hostSorter(a,b)
  233. {var aCount=domainToResourcesMap[a].length;var bCount=domainToResourcesMap[b].length;return(aCount<bCount)?1:(aCount===bCount)?0:-1;}
  234. var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(requests,[WebInspector.resourceTypes.Stylesheet,WebInspector.resourceTypes.Image],true);var hosts=[];for(var url in domainToResourcesMap)
  235. hosts.push(url);if(!hosts.length){callback(null);return;}
  236. hosts.sort(hostSorter);var optimalHostnameCount=this._optimalHostnameCount;if(hosts.length>optimalHostnameCount)
  237. hosts.splice(optimalHostnameCount);var busiestHostResourceCount=domainToResourcesMap[hosts[0]].length;var requestCountAboveThreshold=busiestHostResourceCount-this._minRequestThreshold;if(requestCountAboveThreshold<=0){callback(null);return;}
  238. var avgResourcesPerHost=0;for(var i=0,size=hosts.length;i<size;++i)
  239. avgResourcesPerHost+=domainToResourcesMap[hosts[i]].length;avgResourcesPerHost/=optimalHostnameCount;avgResourcesPerHost=Math.max(avgResourcesPerHost,1);var pctAboveAvg=(requestCountAboveThreshold/avgResourcesPerHost)-1.0;var minBalanceThreshold=this._minBalanceThreshold;if(pctAboveAvg<minBalanceThreshold){callback(null);return;}
  240. var requestsOnBusiestHost=domainToResourcesMap[hosts[0]];var entry=result.addChild(WebInspector.UIString("This page makes %d parallelizable requests to %s. Increase download parallelization by distributing the following requests across multiple hostnames.",busiestHostResourceCount,hosts[0]),true);for(var i=0;i<requestsOnBusiestHost.length;++i)
  241. entry.addURL(requestsOnBusiestHost[i].url);result.violationCount=requestsOnBusiestHost.length;callback(result);},__proto__:WebInspector.AuditRule.prototype}
  242. WebInspector.AuditRules.UnusedCssRule=function()
  243. {WebInspector.AuditRule.call(this,"page-unusedcss",WebInspector.UIString("Remove unused CSS rules"));}
  244. WebInspector.AuditRules.UnusedCssRule.prototype={doRun:function(requests,result,callback,progress)
  245. {function evalCallback(styleSheets){if(!styleSheets.length)
  246. return callback(null);var selectors=[];var testedSelectors={};for(var i=0;i<styleSheets.length;++i){var styleSheet=styleSheets[i];for(var curRule=0;curRule<styleSheet.rules.length;++curRule){var selectorText=styleSheet.rules[curRule].selectorText;if(testedSelectors[selectorText])
  247. continue;selectors.push(selectorText);testedSelectors[selectorText]=1;}}
  248. var foundSelectors={};function selectorsCallback(styleSheets)
  249. {if(progress.isCanceled())
  250. return;var inlineBlockOrdinal=0;var totalStylesheetSize=0;var totalUnusedStylesheetSize=0;var summary;for(var i=0;i<styleSheets.length;++i){var styleSheet=styleSheets[i];var unusedRules=[];for(var curRule=0;curRule<styleSheet.rules.length;++curRule){var rule=styleSheet.rules[curRule];if(!testedSelectors[rule.selectorText]||foundSelectors[rule.selectorText])
  251. continue;unusedRules.push(rule.selectorText);}
  252. totalStylesheetSize+=styleSheet.rules.length;totalUnusedStylesheetSize+=unusedRules.length;if(!unusedRules.length)
  253. continue;var resource=WebInspector.resourceForURL(styleSheet.sourceURL);var isInlineBlock=resource&&resource.request&&resource.request.type===WebInspector.resourceTypes.Document;var url=!isInlineBlock?WebInspector.AuditRuleResult.linkifyDisplayName(styleSheet.sourceURL):WebInspector.UIString("Inline block #%d",++inlineBlockOrdinal);var pctUnused=Math.round(100*unusedRules.length/styleSheet.rules.length);if(!summary)
  254. summary=result.addChild("",true);var entry=summary.addFormatted("%s: %d% is not used by the current page.",url,pctUnused);for(var j=0;j<unusedRules.length;++j)
  255. entry.addSnippet(unusedRules[j]);result.violationCount+=unusedRules.length;}
  256. if(!totalUnusedStylesheetSize)
  257. return callback(null);var totalUnusedPercent=Math.round(100*totalUnusedStylesheetSize/totalStylesheetSize);summary.value=WebInspector.UIString("%s rules (%d%) of CSS not used by the current page.",totalUnusedStylesheetSize,totalUnusedPercent);callback(result);}
  258. function queryCallback(boundSelectorsCallback,selector,nodeId)
  259. {if(nodeId)
  260. foundSelectors[selector]=true;if(boundSelectorsCallback)
  261. boundSelectorsCallback();}
  262. function documentLoaded(selectors,document){var pseudoSelectorRegexp=/::?(?:[\w-]+)(?:\(.*?\))?/g;if(!selectors.length){selectorsCallback([]);return;}
  263. for(var i=0;i<selectors.length;++i){if(progress.isCanceled())
  264. return;var effectiveSelector=selectors[i].replace(pseudoSelectorRegexp,"");WebInspector.domModel.querySelector(document.id,effectiveSelector,queryCallback.bind(null,i===selectors.length-1?selectorsCallback.bind(null,styleSheets):null,selectors[i]));}}
  265. WebInspector.domModel.requestDocument(documentLoaded.bind(null,selectors));}
  266. var styleSheetInfos=WebInspector.cssModel.allStyleSheets();if(!styleSheetInfos||!styleSheetInfos.length){evalCallback([]);return;}
  267. var styleSheetProcessor=new WebInspector.AuditRules.StyleSheetProcessor(styleSheetInfos,progress,evalCallback);styleSheetProcessor.run();},__proto__:WebInspector.AuditRule.prototype}
  268. WebInspector.AuditRules.ParsedStyleSheet;WebInspector.AuditRules.StyleSheetProcessor=function(styleSheetHeaders,progress,styleSheetsParsedCallback)
  269. {this._styleSheetHeaders=styleSheetHeaders;this._progress=progress;this._styleSheets=[];this._styleSheetsParsedCallback=styleSheetsParsedCallback;}
  270. WebInspector.AuditRules.StyleSheetProcessor.prototype={run:function()
  271. {this._parser=new WebInspector.CSSParser();this._processNextStyleSheet();},_terminateWorker:function()
  272. {if(this._parser){this._parser.dispose();delete this._parser;}},_finish:function()
  273. {this._terminateWorker();this._styleSheetsParsedCallback(this._styleSheets);},_processNextStyleSheet:function()
  274. {if(!this._styleSheetHeaders.length){this._finish();return;}
  275. this._currentStyleSheetHeader=this._styleSheetHeaders.shift();this._parser.fetchAndParse(this._currentStyleSheetHeader,this._onStyleSheetParsed.bind(this));},_onStyleSheetParsed:function(rules)
  276. {if(this._progress.isCanceled()){this._terminateWorker();return;}
  277. var styleRules=[];for(var i=0;i<rules.length;++i){var rule=rules[i];if(rule.selectorText)
  278. styleRules.push(rule);}
  279. this._styleSheets.push({sourceURL:this._currentStyleSheetHeader.sourceURL,rules:styleRules});this._processNextStyleSheet();},}
  280. WebInspector.AuditRules.CacheControlRule=function(id,name)
  281. {WebInspector.AuditRule.call(this,id,name);}
  282. WebInspector.AuditRules.CacheControlRule.MillisPerMonth=1000*60*60*24*30;WebInspector.AuditRules.CacheControlRule.prototype={doRun:function(requests,result,callback,progress)
  283. {var cacheableAndNonCacheableResources=this._cacheableAndNonCacheableResources(requests);if(cacheableAndNonCacheableResources[0].length)
  284. this.runChecks(cacheableAndNonCacheableResources[0],result);this.handleNonCacheableResources(cacheableAndNonCacheableResources[1],result);callback(result);},handleNonCacheableResources:function(requests,result)
  285. {},_cacheableAndNonCacheableResources:function(requests)
  286. {var processedResources=[[],[]];for(var i=0;i<requests.length;++i){var request=requests[i];if(!this.isCacheableResource(request))
  287. continue;if(this._isExplicitlyNonCacheable(request))
  288. processedResources[1].push(request);else
  289. processedResources[0].push(request);}
  290. return processedResources;},execCheck:function(messageText,requestCheckFunction,requests,result)
  291. {var requestCount=requests.length;var urls=[];for(var i=0;i<requestCount;++i){if(requestCheckFunction.call(this,requests[i]))
  292. urls.push(requests[i].url);}
  293. if(urls.length){var entry=result.addChild(messageText,true);entry.addURLs(urls);result.violationCount+=urls.length;}},freshnessLifetimeGreaterThan:function(request,timeMs)
  294. {var dateHeader=this.responseHeader(request,"Date");if(!dateHeader)
  295. return false;var dateHeaderMs=Date.parse(dateHeader);if(isNaN(dateHeaderMs))
  296. return false;var freshnessLifetimeMs;var maxAgeMatch=this.responseHeaderMatch(request,"Cache-Control","max-age=(\\d+)");if(maxAgeMatch)
  297. freshnessLifetimeMs=(maxAgeMatch[1])?1000*maxAgeMatch[1]:0;else{var expiresHeader=this.responseHeader(request,"Expires");if(expiresHeader){var expDate=Date.parse(expiresHeader);if(!isNaN(expDate))
  298. freshnessLifetimeMs=expDate-dateHeaderMs;}}
  299. return(isNaN(freshnessLifetimeMs))?false:freshnessLifetimeMs>timeMs;},responseHeader:function(request,header)
  300. {return request.responseHeaderValue(header);},hasResponseHeader:function(request,header)
  301. {return request.responseHeaderValue(header)!==undefined;},isCompressible:function(request)
  302. {return request.type.isTextType();},isPubliclyCacheable:function(request)
  303. {if(this._isExplicitlyNonCacheable(request))
  304. return false;if(this.responseHeaderMatch(request,"Cache-Control","public"))
  305. return true;return request.url.indexOf("?")===-1&&!this.responseHeaderMatch(request,"Cache-Control","private");},responseHeaderMatch:function(request,header,regexp)
  306. {return request.responseHeaderValue(header)?request.responseHeaderValue(header).match(new RegExp(regexp,"im")):null;},hasExplicitExpiration:function(request)
  307. {return this.hasResponseHeader(request,"Date")&&(this.hasResponseHeader(request,"Expires")||!!this.responseHeaderMatch(request,"Cache-Control","max-age"));},_isExplicitlyNonCacheable:function(request)
  308. {var hasExplicitExp=this.hasExplicitExpiration(request);return!!this.responseHeaderMatch(request,"Cache-Control","(no-cache|no-store|must-revalidate)")||!!this.responseHeaderMatch(request,"Pragma","no-cache")||(hasExplicitExp&&!this.freshnessLifetimeGreaterThan(request,0))||(!hasExplicitExp&&!!request.url&&request.url.indexOf("?")>=0)||(!hasExplicitExp&&!this.isCacheableResource(request));},isCacheableResource:function(request)
  309. {return request.statusCode!==undefined&&WebInspector.AuditRules.CacheableResponseCodes[request.statusCode];},__proto__:WebInspector.AuditRule.prototype}
  310. WebInspector.AuditRules.BrowserCacheControlRule=function()
  311. {WebInspector.AuditRules.CacheControlRule.call(this,"http-browsercache",WebInspector.UIString("Leverage browser caching"));}
  312. WebInspector.AuditRules.BrowserCacheControlRule.prototype={handleNonCacheableResources:function(requests,result)
  313. {if(requests.length){var entry=result.addChild(WebInspector.UIString("The following resources are explicitly non-cacheable. Consider making them cacheable if possible:"),true);result.violationCount+=requests.length;for(var i=0;i<requests.length;++i)
  314. entry.addURL(requests[i].url);}},runChecks:function(requests,result,callback)
  315. {this.execCheck(WebInspector.UIString("The following resources are missing a cache expiration. Resources that do not specify an expiration may not be cached by browsers:"),this._missingExpirationCheck,requests,result);this.execCheck(WebInspector.UIString("The following resources specify a \"Vary\" header that disables caching in most versions of Internet Explorer:"),this._varyCheck,requests,result);this.execCheck(WebInspector.UIString("The following cacheable resources have a short freshness lifetime:"),this._oneMonthExpirationCheck,requests,result);this.execCheck(WebInspector.UIString("To further improve cache hit rate, specify an expiration one year in the future for the following cacheable resources:"),this._oneYearExpirationCheck,requests,result);},_missingExpirationCheck:function(request)
  316. {return this.isCacheableResource(request)&&!this.hasResponseHeader(request,"Set-Cookie")&&!this.hasExplicitExpiration(request);},_varyCheck:function(request)
  317. {var varyHeader=this.responseHeader(request,"Vary");if(varyHeader){varyHeader=varyHeader.replace(/User-Agent/gi,"");varyHeader=varyHeader.replace(/Accept-Encoding/gi,"");varyHeader=varyHeader.replace(/[, ]*/g,"");}
  318. return varyHeader&&varyHeader.length&&this.isCacheableResource(request)&&this.freshnessLifetimeGreaterThan(request,0);},_oneMonthExpirationCheck:function(request)
  319. {return this.isCacheableResource(request)&&!this.hasResponseHeader(request,"Set-Cookie")&&!this.freshnessLifetimeGreaterThan(request,WebInspector.AuditRules.CacheControlRule.MillisPerMonth)&&this.freshnessLifetimeGreaterThan(request,0);},_oneYearExpirationCheck:function(request)
  320. {return this.isCacheableResource(request)&&!this.hasResponseHeader(request,"Set-Cookie")&&!this.freshnessLifetimeGreaterThan(request,11*WebInspector.AuditRules.CacheControlRule.MillisPerMonth)&&this.freshnessLifetimeGreaterThan(request,WebInspector.AuditRules.CacheControlRule.MillisPerMonth);},__proto__:WebInspector.AuditRules.CacheControlRule.prototype}
  321. WebInspector.AuditRules.ProxyCacheControlRule=function(){WebInspector.AuditRules.CacheControlRule.call(this,"http-proxycache",WebInspector.UIString("Leverage proxy caching"));}
  322. WebInspector.AuditRules.ProxyCacheControlRule.prototype={runChecks:function(requests,result,callback)
  323. {this.execCheck(WebInspector.UIString("Resources with a \"?\" in the URL are not cached by most proxy caching servers:"),this._questionMarkCheck,requests,result);this.execCheck(WebInspector.UIString("Consider adding a \"Cache-Control: public\" header to the following resources:"),this._publicCachingCheck,requests,result);this.execCheck(WebInspector.UIString("The following publicly cacheable resources contain a Set-Cookie header. This security vulnerability can cause cookies to be shared by multiple users."),this._setCookieCacheableCheck,requests,result);},_questionMarkCheck:function(request)
  324. {return request.url.indexOf("?")>=0&&!this.hasResponseHeader(request,"Set-Cookie")&&this.isPubliclyCacheable(request);},_publicCachingCheck:function(request)
  325. {return this.isCacheableResource(request)&&!this.isCompressible(request)&&!this.responseHeaderMatch(request,"Cache-Control","public")&&!this.hasResponseHeader(request,"Set-Cookie");},_setCookieCacheableCheck:function(request)
  326. {return this.hasResponseHeader(request,"Set-Cookie")&&this.isPubliclyCacheable(request);},__proto__:WebInspector.AuditRules.CacheControlRule.prototype}
  327. WebInspector.AuditRules.ImageDimensionsRule=function()
  328. {WebInspector.AuditRule.call(this,"page-imagedims",WebInspector.UIString("Specify image dimensions"));}
  329. WebInspector.AuditRules.ImageDimensionsRule.prototype={doRun:function(requests,result,callback,progress)
  330. {var urlToNoDimensionCount={};function doneCallback()
  331. {for(var url in urlToNoDimensionCount){var entry=entry||result.addChild(WebInspector.UIString("A width and height should be specified for all images in order to speed up page display. The following image(s) are missing a width and/or height:"),true);var format="%r";if(urlToNoDimensionCount[url]>1)
  332. format+=" (%d uses)";entry.addFormatted(format,url,urlToNoDimensionCount[url]);result.violationCount++;}
  333. callback(entry?result:null);}
  334. function imageStylesReady(imageId,styles,isLastStyle,computedStyle)
  335. {if(progress.isCanceled())
  336. return;const node=WebInspector.domModel.nodeForId(imageId);var src=node.getAttribute("src");if(!src.asParsedURL()){for(var frameOwnerCandidate=node;frameOwnerCandidate;frameOwnerCandidate=frameOwnerCandidate.parentNode){if(frameOwnerCandidate.baseURL){var completeSrc=WebInspector.ParsedURL.completeURL(frameOwnerCandidate.baseURL,src);break;}}}
  337. if(completeSrc)
  338. src=completeSrc;if(computedStyle.getPropertyValue("position")==="absolute"){if(isLastStyle)
  339. doneCallback();return;}
  340. if(styles.attributesStyle){var widthFound=!!styles.attributesStyle.getLiveProperty("width");var heightFound=!!styles.attributesStyle.getLiveProperty("height");}
  341. var inlineStyle=styles.inlineStyle;if(inlineStyle){if(inlineStyle.getPropertyValue("width")!=="")
  342. widthFound=true;if(inlineStyle.getPropertyValue("height")!=="")
  343. heightFound=true;}
  344. for(var i=styles.matchedCSSRules.length-1;i>=0&&!(widthFound&&heightFound);--i){var style=styles.matchedCSSRules[i].style;if(style.getPropertyValue("width")!=="")
  345. widthFound=true;if(style.getPropertyValue("height")!=="")
  346. heightFound=true;}
  347. if(!widthFound||!heightFound){if(src in urlToNoDimensionCount)
  348. ++urlToNoDimensionCount[src];else
  349. urlToNoDimensionCount[src]=1;}
  350. if(isLastStyle)
  351. doneCallback();}
  352. function getStyles(nodeIds)
  353. {if(progress.isCanceled())
  354. return;var targetResult={};function inlineCallback(inlineStyle,attributesStyle)
  355. {targetResult.inlineStyle=inlineStyle;targetResult.attributesStyle=attributesStyle;}
  356. function matchedCallback(result)
  357. {if(result)
  358. targetResult.matchedCSSRules=result.matchedCSSRules;}
  359. if(!nodeIds||!nodeIds.length)
  360. doneCallback();for(var i=0;nodeIds&&i<nodeIds.length;++i){WebInspector.cssModel.getMatchedStylesAsync(nodeIds[i],false,false,matchedCallback);WebInspector.cssModel.getInlineStylesAsync(nodeIds[i],inlineCallback);WebInspector.cssModel.getComputedStyleAsync(nodeIds[i],imageStylesReady.bind(null,nodeIds[i],targetResult,i===nodeIds.length-1));}}
  361. function onDocumentAvailable(root)
  362. {if(progress.isCanceled())
  363. return;WebInspector.domModel.querySelectorAll(root.id,"img[src]",getStyles);}
  364. if(progress.isCanceled())
  365. return;WebInspector.domModel.requestDocument(onDocumentAvailable);},__proto__:WebInspector.AuditRule.prototype}
  366. WebInspector.AuditRules.CssInHeadRule=function()
  367. {WebInspector.AuditRule.call(this,"page-cssinhead",WebInspector.UIString("Put CSS in the document head"));}
  368. WebInspector.AuditRules.CssInHeadRule.prototype={doRun:function(requests,result,callback,progress)
  369. {function evalCallback(evalResult)
  370. {if(progress.isCanceled())
  371. return;if(!evalResult)
  372. return callback(null);var summary=result.addChild("");var outputMessages=[];for(var url in evalResult){var urlViolations=evalResult[url];if(urlViolations[0]){result.addFormatted("%s style block(s) in the %r body should be moved to the document head.",urlViolations[0],url);result.violationCount+=urlViolations[0];}
  373. for(var i=0;i<urlViolations[1].length;++i)
  374. result.addFormatted("Link node %r should be moved to the document head in %r",urlViolations[1][i],url);result.violationCount+=urlViolations[1].length;}
  375. summary.value=WebInspector.UIString("CSS in the document body adversely impacts rendering performance.");callback(result);}
  376. function externalStylesheetsReceived(root,inlineStyleNodeIds,nodeIds)
  377. {if(progress.isCanceled())
  378. return;if(!nodeIds)
  379. return;var externalStylesheetNodeIds=nodeIds;var result=null;if(inlineStyleNodeIds.length||externalStylesheetNodeIds.length){var urlToViolationsArray={};var externalStylesheetHrefs=[];for(var j=0;j<externalStylesheetNodeIds.length;++j){var linkNode=WebInspector.domModel.nodeForId(externalStylesheetNodeIds[j]);var completeHref=WebInspector.ParsedURL.completeURL(linkNode.ownerDocument.baseURL,linkNode.getAttribute("href"));externalStylesheetHrefs.push(completeHref||"<empty>");}
  380. urlToViolationsArray[root.documentURL]=[inlineStyleNodeIds.length,externalStylesheetHrefs];result=urlToViolationsArray;}
  381. evalCallback(result);}
  382. function inlineStylesReceived(root,nodeIds)
  383. {if(progress.isCanceled())
  384. return;if(!nodeIds)
  385. return;WebInspector.domModel.querySelectorAll(root.id,"body link[rel~='stylesheet'][href]",externalStylesheetsReceived.bind(null,root,nodeIds));}
  386. function onDocumentAvailable(root)
  387. {if(progress.isCanceled())
  388. return;WebInspector.domModel.querySelectorAll(root.id,"body style",inlineStylesReceived.bind(null,root));}
  389. WebInspector.domModel.requestDocument(onDocumentAvailable);},__proto__:WebInspector.AuditRule.prototype}
  390. WebInspector.AuditRules.StylesScriptsOrderRule=function()
  391. {WebInspector.AuditRule.call(this,"page-stylescriptorder",WebInspector.UIString("Optimize the order of styles and scripts"));}
  392. WebInspector.AuditRules.StylesScriptsOrderRule.prototype={doRun:function(requests,result,callback,progress)
  393. {function evalCallback(resultValue)
  394. {if(progress.isCanceled())
  395. return;if(!resultValue)
  396. return callback(null);var lateCssUrls=resultValue[0];var cssBeforeInlineCount=resultValue[1];if(lateCssUrls.length){var entry=result.addChild(WebInspector.UIString("The following external CSS files were included after an external JavaScript file in the document head. To ensure CSS files are downloaded in parallel, always include external CSS before external JavaScript."),true);entry.addURLs(lateCssUrls);result.violationCount+=lateCssUrls.length;}
  397. if(cssBeforeInlineCount){result.addChild(WebInspector.UIString(" %d inline script block%s found in the head between an external CSS file and another resource. To allow parallel downloading, move the inline script before the external CSS file, or after the next resource.",cssBeforeInlineCount,cssBeforeInlineCount>1?"s were":" was"));result.violationCount+=cssBeforeInlineCount;}
  398. callback(result);}
  399. function cssBeforeInlineReceived(lateStyleIds,nodeIds)
  400. {if(progress.isCanceled())
  401. return;if(!nodeIds)
  402. return;var cssBeforeInlineCount=nodeIds.length;var result=null;if(lateStyleIds.length||cssBeforeInlineCount){var lateStyleUrls=[];for(var i=0;i<lateStyleIds.length;++i){var lateStyleNode=WebInspector.domModel.nodeForId(lateStyleIds[i]);var completeHref=WebInspector.ParsedURL.completeURL(lateStyleNode.ownerDocument.baseURL,lateStyleNode.getAttribute("href"));lateStyleUrls.push(completeHref||"<empty>");}
  403. result=[lateStyleUrls,cssBeforeInlineCount];}
  404. evalCallback(result);}
  405. function lateStylesReceived(root,nodeIds)
  406. {if(progress.isCanceled())
  407. return;if(!nodeIds)
  408. return;WebInspector.domModel.querySelectorAll(root.id,"head link[rel~='stylesheet'][href] ~ script:not([src])",cssBeforeInlineReceived.bind(null,nodeIds));}
  409. function onDocumentAvailable(root)
  410. {if(progress.isCanceled())
  411. return;WebInspector.domModel.querySelectorAll(root.id,"head script[src] ~ link[rel~='stylesheet'][href]",lateStylesReceived.bind(null,root));}
  412. WebInspector.domModel.requestDocument(onDocumentAvailable);},__proto__:WebInspector.AuditRule.prototype}
  413. WebInspector.AuditRules.CSSRuleBase=function(id,name)
  414. {WebInspector.AuditRule.call(this,id,name);}
  415. WebInspector.AuditRules.CSSRuleBase.prototype={doRun:function(requests,result,callback,progress)
  416. {var headers=WebInspector.cssModel.allStyleSheets();if(!headers.length){callback(null);return;}
  417. var activeHeaders=[]
  418. for(var i=0;i<headers.length;++i){if(!headers[i].disabled)
  419. activeHeaders.push(headers[i]);}
  420. var styleSheetProcessor=new WebInspector.AuditRules.StyleSheetProcessor(activeHeaders,progress,this._styleSheetsLoaded.bind(this,result,callback,progress));styleSheetProcessor.run();},_styleSheetsLoaded:function(result,callback,progress,styleSheets)
  421. {for(var i=0;i<styleSheets.length;++i)
  422. this._visitStyleSheet(styleSheets[i],result);callback(result);},_visitStyleSheet:function(styleSheet,result)
  423. {this.visitStyleSheet(styleSheet,result);for(var i=0;i<styleSheet.rules.length;++i)
  424. this._visitRule(styleSheet,styleSheet.rules[i],result);this.didVisitStyleSheet(styleSheet,result);},_visitRule:function(styleSheet,rule,result)
  425. {this.visitRule(styleSheet,rule,result);var allProperties=rule.properties;for(var i=0;i<allProperties.length;++i)
  426. this.visitProperty(styleSheet,rule,allProperties[i],result);this.didVisitRule(styleSheet,rule,result);},visitStyleSheet:function(styleSheet,result)
  427. {},didVisitStyleSheet:function(styleSheet,result)
  428. {},visitRule:function(styleSheet,rule,result)
  429. {},didVisitRule:function(styleSheet,rule,result)
  430. {},visitProperty:function(styleSheet,rule,property,result)
  431. {},__proto__:WebInspector.AuditRule.prototype}
  432. WebInspector.AuditRules.VendorPrefixedCSSProperties=function()
  433. {WebInspector.AuditRules.CSSRuleBase.call(this,"page-vendorprefixedcss",WebInspector.UIString("Use normal CSS property names instead of vendor-prefixed ones"));this._webkitPrefix="-webkit-";}
  434. WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties=["background-clip","background-origin","background-size","border-radius","border-bottom-left-radius","border-bottom-right-radius","border-top-left-radius","border-top-right-radius","box-shadow","box-sizing","opacity","text-shadow"].keySet();WebInspector.AuditRules.VendorPrefixedCSSProperties.prototype={didVisitStyleSheet:function(styleSheet)
  435. {delete this._styleSheetResult;},visitRule:function(rule)
  436. {this._mentionedProperties={};},didVisitRule:function()
  437. {delete this._ruleResult;delete this._mentionedProperties;},visitProperty:function(styleSheet,rule,property,result)
  438. {if(!property.name.startsWith(this._webkitPrefix))
  439. return;var normalPropertyName=property.name.substring(this._webkitPrefix.length).toLowerCase();if(WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties[normalPropertyName]&&!this._mentionedProperties[normalPropertyName]){this._mentionedProperties[normalPropertyName]=true;if(!this._styleSheetResult)
  440. this._styleSheetResult=result.addChild(styleSheet.sourceURL?WebInspector.linkifyResourceAsNode(styleSheet.sourceURL):WebInspector.UIString("<unknown>"));if(!this._ruleResult){var anchor=WebInspector.linkifyURLAsNode(styleSheet.sourceURL,rule.selectorText);anchor.lineNumber=rule.lineNumber;this._ruleResult=this._styleSheetResult.addChild(anchor);}
  441. ++result.violationCount;this._ruleResult.addSnippet(WebInspector.UIString("\"%s%s\" is used, but \"%s\" is supported.",this._webkitPrefix,normalPropertyName,normalPropertyName));}},__proto__:WebInspector.AuditRules.CSSRuleBase.prototype}
  442. WebInspector.AuditRules.CookieRuleBase=function(id,name)
  443. {WebInspector.AuditRule.call(this,id,name);}
  444. WebInspector.AuditRules.CookieRuleBase.prototype={doRun:function(requests,result,callback,progress)
  445. {var self=this;function resultCallback(receivedCookies){if(progress.isCanceled())
  446. return;self.processCookies(receivedCookies,requests,result);callback(result);}
  447. WebInspector.Cookies.getCookiesAsync(resultCallback);},mapResourceCookies:function(requestsByDomain,allCookies,callback)
  448. {for(var i=0;i<allCookies.length;++i){for(var requestDomain in requestsByDomain){if(WebInspector.Cookies.cookieDomainMatchesResourceDomain(allCookies[i].domain(),requestDomain))
  449. this._callbackForResourceCookiePairs(requestsByDomain[requestDomain],allCookies[i],callback);}}},_callbackForResourceCookiePairs:function(requests,cookie,callback)
  450. {if(!requests)
  451. return;for(var i=0;i<requests.length;++i){if(WebInspector.Cookies.cookieMatchesResourceURL(cookie,requests[i].url))
  452. callback(requests[i],cookie);}},__proto__:WebInspector.AuditRule.prototype}
  453. WebInspector.AuditRules.CookieSizeRule=function(avgBytesThreshold)
  454. {WebInspector.AuditRules.CookieRuleBase.call(this,"http-cookiesize",WebInspector.UIString("Minimize cookie size"));this._avgBytesThreshold=avgBytesThreshold;this._maxBytesThreshold=1000;}
  455. WebInspector.AuditRules.CookieSizeRule.prototype={_average:function(cookieArray)
  456. {var total=0;for(var i=0;i<cookieArray.length;++i)
  457. total+=cookieArray[i].size();return cookieArray.length?Math.round(total/cookieArray.length):0;},_max:function(cookieArray)
  458. {var result=0;for(var i=0;i<cookieArray.length;++i)
  459. result=Math.max(cookieArray[i].size(),result);return result;},processCookies:function(allCookies,requests,result)
  460. {function maxSizeSorter(a,b)
  461. {return b.maxCookieSize-a.maxCookieSize;}
  462. function avgSizeSorter(a,b)
  463. {return b.avgCookieSize-a.avgCookieSize;}
  464. var cookiesPerResourceDomain={};function collectorCallback(request,cookie)
  465. {var cookies=cookiesPerResourceDomain[request.parsedURL.host];if(!cookies){cookies=[];cookiesPerResourceDomain[request.parsedURL.host]=cookies;}
  466. cookies.push(cookie);}
  467. if(!allCookies.length)
  468. return;var sortedCookieSizes=[];var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(requests,null,true);var matchingResourceData={};this.mapResourceCookies(domainToResourcesMap,allCookies,collectorCallback);for(var requestDomain in cookiesPerResourceDomain){var cookies=cookiesPerResourceDomain[requestDomain];sortedCookieSizes.push({domain:requestDomain,avgCookieSize:this._average(cookies),maxCookieSize:this._max(cookies)});}
  469. var avgAllCookiesSize=this._average(allCookies);var hugeCookieDomains=[];sortedCookieSizes.sort(maxSizeSorter);for(var i=0,len=sortedCookieSizes.length;i<len;++i){var maxCookieSize=sortedCookieSizes[i].maxCookieSize;if(maxCookieSize>this._maxBytesThreshold)
  470. hugeCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(sortedCookieSizes[i].domain)+": "+Number.bytesToString(maxCookieSize));}
  471. var bigAvgCookieDomains=[];sortedCookieSizes.sort(avgSizeSorter);for(var i=0,len=sortedCookieSizes.length;i<len;++i){var domain=sortedCookieSizes[i].domain;var avgCookieSize=sortedCookieSizes[i].avgCookieSize;if(avgCookieSize>this._avgBytesThreshold&&avgCookieSize<this._maxBytesThreshold)
  472. bigAvgCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(domain)+": "+Number.bytesToString(avgCookieSize));}
  473. result.addChild(WebInspector.UIString("The average cookie size for all requests on this page is %s",Number.bytesToString(avgAllCookiesSize)));var message;if(hugeCookieDomains.length){var entry=result.addChild(WebInspector.UIString("The following domains have a cookie size in excess of 1KB. This is harmful because requests with cookies larger than 1KB typically cannot fit into a single network packet."),true);entry.addURLs(hugeCookieDomains);result.violationCount+=hugeCookieDomains.length;}
  474. if(bigAvgCookieDomains.length){var entry=result.addChild(WebInspector.UIString("The following domains have an average cookie size in excess of %d bytes. Reducing the size of cookies for these domains can reduce the time it takes to send requests.",this._avgBytesThreshold),true);entry.addURLs(bigAvgCookieDomains);result.violationCount+=bigAvgCookieDomains.length;}},__proto__:WebInspector.AuditRules.CookieRuleBase.prototype}
  475. WebInspector.AuditRules.StaticCookielessRule=function(minResources)
  476. {WebInspector.AuditRules.CookieRuleBase.call(this,"http-staticcookieless",WebInspector.UIString("Serve static content from a cookieless domain"));this._minResources=minResources;}
  477. WebInspector.AuditRules.StaticCookielessRule.prototype={processCookies:function(allCookies,requests,result)
  478. {var domainToResourcesMap=WebInspector.AuditRules.getDomainToResourcesMap(requests,[WebInspector.resourceTypes.Stylesheet,WebInspector.resourceTypes.Image],true);var totalStaticResources=0;for(var domain in domainToResourcesMap)
  479. totalStaticResources+=domainToResourcesMap[domain].length;if(totalStaticResources<this._minResources)
  480. return;var matchingResourceData={};this.mapResourceCookies(domainToResourcesMap,allCookies,this._collectorCallback.bind(this,matchingResourceData));var badUrls=[];var cookieBytes=0;for(var url in matchingResourceData){badUrls.push(url);cookieBytes+=matchingResourceData[url]}
  481. if(badUrls.length<this._minResources)
  482. return;var entry=result.addChild(WebInspector.UIString("%s of cookies were sent with the following static resources. Serve these static resources from a domain that does not set cookies:",Number.bytesToString(cookieBytes)),true);entry.addURLs(badUrls);result.violationCount=badUrls.length;},_collectorCallback:function(matchingResourceData,request,cookie)
  483. {matchingResourceData[request.url]=(matchingResourceData[request.url]||0)+cookie.size();},__proto__:WebInspector.AuditRules.CookieRuleBase.prototype};